package com.weaver.qfengx;

import com.google.common.collect.Maps;
import com.weaver.qfengx.map.CaseInsensitiveMap;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Objects;

/**
 * Map工具类
 * Created by YeShengtao on 2020/8/5 10:30
 */
public class MapUtils {

    /**
     * 将对象值转为Map<String, String>
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, String> beanToMap(Object obj) throws IllegalAccessException {
        Map<String, String> res = Maps.newHashMap();
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();
            Object value = field.get(obj);
            res.put(name, StringUtils.val(value));
        }
        return res;
    }

    public static String val(Map<?, ?> map, String key) {
        if (Objects.isNull(map))
            return null;
        Object val = map.get(key);
        return StringUtils.val(val, "");
    }

    public static String val(Map<?, ?> map, String key, String defaultVal) {
        Object val = map.get(key);
        return StringUtils.val(val, defaultVal);
    }

    public static boolean isEmpty(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }

    public static <K, V> CaseInsensitiveMap<K, V> newCaseInsensitiveMap() {
        return new CaseInsensitiveMap();
    }

}
